package com.pactera.asmp.server.restfullapi;

import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.annotations.JwtIgnore;
import com.pactera.asmp.server.common.constants.Result;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.entity.ResponseResult;
import com.pactera.asmp.server.service.TokenServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ProjectName: asmp-server
 * @Package com.pactera.asmp.server.restfullapi
 * @ClassName: RestfullTokenApi
 * @Description: RestfullTokenApi
 * @Date 2020/05/30 22:59
 * @Author lvzhiqiang
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/v1")
public class RestfullTokenApi {
    private static final Logger logger = LoggerFactory
            .getLogger(RestfullTokenApi.class);

    @Autowired
    private TokenServiceImpl mTokenService;


    /**
     * UUID :Unique Ingredient Identifier
     * JWT = UUID + channelId + createTime + IpAddress
     * 备注：channelId  0：Android IVI APP 1：Android app 2. IOS APP  3. PC  4. TrafficLight  不同channelId对应的UII意义不同
     * 1. OldToken 在redis中已失效，但是JWT没有超期，则需要解析OldToken获取UUID，根据UUID产生新的token
     * 2. OldToken 在redis中已失效，且JWT也超期了，则此时返回错误码 用户重新登录/设备端重新调用registerAPI获取新的Token，并更新到Redis
     * 3. OldToken 在redis中未失效，此时直接删除redis中该token对应的那条记录，并重新产生新的token返回给客户端
     *
     * @param jsonParams
     * @return
     */
    @PatchMapping("/token")
    @JwtIgnore
    public ResponseResult refreshToken(@RequestBody() JSONObject jsonParams) {
        String oldToken = jsonParams.getString("oldToken");
        Integer channelId = Integer.valueOf(jsonParams.getString("channelId"));
        logger.info("RestfullTokenApi refreshToken oldToken:{},  channelId:{}" ,oldToken,channelId);
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        Result result = mTokenService.refreshToken(oldToken, channelId);
        if(result.getCode() == Result.SUCCESS().getCode()){
            responseResult.setData(result.getData());
        }else {
            responseResult = new ResponseResult(ResultCode.FAIL);
            responseResult.setMessage(result.getMessage());
        }
        return responseResult;
    }

    /**
     * Totd test code.
     *
     * @param uuid
     * @param channelId
     * @return
     */
    @GetMapping("/token")
    @JwtIgnore
    public String createToken(@RequestParam("uuid") String uuid, @RequestParam("channelId") int channelId) {
        logger.info("RestfullTokenApi createToken uuid:{},  channelId:{}" ,uuid, channelId);
        return Result.SUCCESS(mTokenService.createToken(uuid,"1", channelId)).toString();
    }
}